<template>
  <div class="attendance-statistics-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><DataAnalysis /></el-icon>
            <span class="header-title">考勤统计</span>
          </div>
          <div class="header-right">
            <el-button type="success" @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="月份">
            <el-date-picker
              v-model="filterForm.month"
              type="month"
              placeholder="选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              size="large"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadStatistics" size="large">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">总打卡次数</div>
                <div class="stat-value">{{ statistics.totalCheckIns }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">正常出勤</div>
                <div class="stat-value success">{{ statistics.normalAttendance }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">请假人数</div>
                <div class="stat-value warning">{{ statistics.leaveCount }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">加班人次</div>
                <div class="stat-value info">{{ statistics.overtimeCount }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <el-divider />
      
      <div class="table-section">
        <div class="section-title">详细统计</div>
        <el-table 
          :data="statisticsList" 
          style="width: 100%"
          stripe
          :empty-text="'暂无统计数据'"
        >
          <el-table-column label="员工" width="150" align="center">
            <template #default="scope">
              <span>{{ scope.row.userName || `员工${scope.row.userId}` }}</span>
            </template>
          </el-table-column>
          <el-table-column label="打卡次数" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.checkInCount || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="请假天数" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.leaveDays || 0 }} 天</span>
            </template>
          </el-table-column>
          <el-table-column label="加班时长" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.overtimeHours || 0 }} 小时</span>
            </template>
          </el-table-column>
          <el-table-column label="出勤率" width="120" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.attendanceRate >= 90 ? 'success' : scope.row.attendanceRate >= 70 ? 'warning' : 'danger'">
                {{ scope.row.attendanceRate || 0 }}%
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { DataAnalysis, Search, Download } from '@element-plus/icons-vue'

export default {
  name: 'AttendanceStatistics',
  components: {
    DataAnalysis,
    Search,
    Download
  },
  setup() {
    const filterForm = ref({
      month: new Date().toISOString().slice(0, 7) // 当前月份 YYYY-MM
    })
    const statistics = ref({
      totalCheckIns: 0,
      normalAttendance: 0,
      leaveCount: 0,
      overtimeCount: 0
    })
    const statisticsList = ref([])
    const exportLoading = ref(false)
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        const params = {}
        if (filterForm.value.month) {
          params.month = filterForm.value.month
        }
        
        const token = localStorage.getItem('token')
        const queryString = new URLSearchParams(params).toString()
        const url = `/api/attendance/statistics/export${queryString ? '?' + queryString : ''}`
        
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          throw new Error('导出失败')
        }
        
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `考勤统计_${filterForm.value.month || new Date().toISOString().slice(0, 7)}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        exportLoading.value = false
      }
    }
    
    const loadStatistics = async () => {
      try {
        const res = await request.get('/attendance/statistics', {
          params: {
            month: filterForm.value.month
          }
        })
        if (res.data) {
          statistics.value = res.data.statistics || statistics.value
          statisticsList.value = res.data.details || []
        }
      } catch (error) {
        // 如果接口不存在，使用模拟数据
        ElMessage.warning('统计接口暂未实现，显示模拟数据')
        statistics.value = {
          totalCheckIns: 156,
          normalAttendance: 142,
          leaveCount: 8,
          overtimeCount: 12
        }
        statisticsList.value = [
          { userId: 1, checkInCount: 22, leaveDays: 0, overtimeHours: 8, attendanceRate: 100 },
          { userId: 2, checkInCount: 20, leaveDays: 2, overtimeHours: 4, attendanceRate: 91 },
          { userId: 3, checkInCount: 18, leaveDays: 4, overtimeHours: 0, attendanceRate: 82 }
        ]
      }
    }
    
    onMounted(() => {
      loadStatistics()
    })
    
    return {
      filterForm,
      statistics,
      statisticsList,
      exportLoading,
      loadStatistics,
      exportData
    }
  }
}
</script>

<style scoped>
.attendance-statistics-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-form {
  margin: 0;
}

.statistics-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  border: none;
}

.stat-content {
  text-align: center;
  padding: 16px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #409eff;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.warning {
  color: #e6a23c;
}

.stat-value.info {
  color: #909399;
}

.table-section {
  margin-top: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 16px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}
</style>

